#include "mystdio.h"
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#define FILE_MODE 0666//文件创建默认权限

myFILE *my_fopen(const char *path, const char *mode)
{
    int flag = 0;
    int fd = 0;
    if(strcmp(mode, "r") == 0)
    {
        flag |= O_RDONLY;
    }
    else if(strcmp(mode, "w") == 0)
    {
        flag |= (O_CREAT | O_WRONLY | O_TRUNC);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag |= (O_CREAT | O_WRONLY | O_APPEND);
    }
    else
    {
        //do nothing
    }
    
    //打开文件
    if(flag & O_CREAT)
    {
        fd = open(path, flag, FILE_MODE);
    }
    else
    {
        fd = open(path, flag);
    }
    //文件打开失败
    if(fd < 0)
    {
        errno = 2;//没有该文件
        return NULL;
    }

    myFILE *fp = (myFILE*)malloc(sizeof(myFILE));
    if(!fd)
    {
        errno = 3;
        return NULL;
    }

    fp->flag = FLUSH_LINE;
    fp->fileno = fd;
    fp->end = 0;
    return fp;
}

int my_fwrite(const char *s, int num, myFILE *stream)
{
    //写入
    memcpy(stream->buffer + stream->end, s, num + 1);
    stream->end += num;

    //判断是否需要刷新
    int i = stream->end - 1;
    if((stream->flag & FLUSH_LINE) && stream->end>0)
    {
        while(i)
        {
            if(stream->buffer[i] == '\n')
            {
                 my_fflush(stream);
                 break;
            }
            i--;
        }
    }
    return i == 0 ? 0 : num; 
}

int my_fflush(myFILE *stream)
{
    if(stream->end > 0)
    {
        write(stream->fileno, stream->buffer, stream->end);
        //fscnc(stream->fileno);//强制内核缓冲区刷新
        stream->end = 0;
    }
    return 0;
}

int my_fclose(myFILE *stream)
{
    my_fflush(stream);
    return close(stream->fileno);
}
